package com.xiaotu.spider.maoyan.pageprocessor;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import com.xiaotu.common.model.MaoYanScoreSupplement;
import com.xiaotu.common.util.Constants;
import com.xiaotu.common.util.HtmlUtil;
import com.xiaotu.common.util.PageUtils;
import com.xiaotu.spider.AUrlPageProcessor;
import com.xiaotu.spider.maoyan.common.MaoYanDataSource;
import net.sf.json.JSONObject;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.selector.Html;
@Component("MaoYanMovieScoreSupplementPageProcessor")
public class MaoYanMovieScoreSupplementPageProcessor extends AUrlPageProcessor {
	
	private String [] START_URL = {
			"http://piaofang.maoyan.com/dashboard"
	};
	
    
	@Override
	public void process(Page page) {
		
		Map<String, Object> extrasMap = page.getRequest().getExtras();
		
		switch (this.getPageDataType(page))
        {
            case "_v_=yes":
	            this.scoreProcess(page,extrasMap);
	            break;
            default:
                this.addRequestProcess(page);
                break;
        }
		
	}
	

	@Override
	public String getPageDataType(Page page) {
		String url = page.getUrl().toString();
        if (url.contains("_v_=yes")){
        	return "_v_=yes";
        }
        return Constants.PageDataType.SEARCH_LIST;
	}

	//添加请求任务
	public void addRequestProcess(Page page){
	
		List<JSONObject> targetList = MaoYanDataSource.jsonList;
		
		System.out.println(targetList);
		
		targetList.forEach(target ->
        {
            String dataId = target.getString("dataid");
            String tvname = target.getString("tvname");
            if (StringUtils.isEmpty(dataId))
                return;
            Map<String, Object> extrasMap = new HashMap<String, Object>();
            extrasMap.put("dataId",dataId);
            extrasMap.put("tvname",tvname);
            PageUtils.addTargetRequest(page, String.format("http://piaofang.maoyan.com/movie/%s?_v_=yes", dataId), extrasMap);
        });
	}
	
	private void scoreProcess(Page page, Map<String, Object> extrasMap) {
		
		String dataId = extrasMap.get("dataId").toString();
		String tvname = extrasMap.get("tvname").toString();
		
		//猫眼评分
        String score = null;
        String starLevel = null;
        String cinemaScore = null;//观众评分人数
        String wantToSee = null;//想看人数
        String otherScoreName = null;//其他评分来源
        String otherScoreValue = null;//其他来源评分
        
        Html html = page.getHtml();
        
        try {
			
        	List<String> starLevelList = new ArrayList<String>();
        	List<String> ratingStarsDivList = html.xpath("//div[@class='rating-stars']").all();
        	if(ratingStarsDivList.size()>0){
        		List<String> starsList = new Html(ratingStarsDivList.get(0)).xpath("//div[@class='rating-stars']//span").all();
        		//是否存在评分数据
                if(starsList.size()==6){
                	for(int i = 0;i<starsList.size();i++ ){
                    	Html starHtml = new Html(starsList.get(i));
                    	if(starHtml.xpath("//span//@class").get().equals("rating-num")){
                    		score = HtmlUtil.delHTMLTag(starHtml.xpath("//span").get());
                    	}else{
                    		starLevelList.add(HtmlUtil.delHTMLTag(starHtml.xpath("//span//@class").get()));
                    	}
                    }
                }
        	}
            
            if(starLevelList.size() == 5){
            	starLevel = getStarLevel(starLevelList);
            }
            
            cinemaScore = html.xpath("//div[@class='score-detail']//p[@class='detail-score-count']//text()").get();
            if(StringUtils.isNotBlank(cinemaScore)){
            	cinemaScore = cinemaScore.replace("观众评分","").trim();
            }
            wantToSee = html.xpath("//div[@class='score-detail']//p[@class='detail-wish-count']//text()").get();
            if(StringUtils.isBlank(wantToSee)){//重新获取
            	wantToSee = html.xpath("//div[@class='block-wish-item left']//h2//text()").get();
            	if(wantToSee.contains("暂无想看")){
            		wantToSee = null;
            	}
            }
            if(StringUtils.isNotBlank(wantToSee)){
            	wantToSee = wantToSee.replace("人想看","").trim();
            }
            String otherScoreStr = html.xpath("//div[@class='score-detail']//p[@class='detail-other-score']//text()").get();
            if(null != otherScoreStr){
            	String [] otherScoreArr = otherScoreStr.replace("其他评分 : ","").split(" ");
            	otherScoreName = otherScoreArr[0];
                otherScoreValue = otherScoreArr[1];
            }
            
		} catch (Exception e) {
			System.out.println("当前数据id:"+dataId+"电影名称:"+tvname+"-----------"+MaoYanMovieRelatedDataPageProcessor.class.getName()+" detailProcess() "+e.getMessage());
		}
        
        if(score!=null || starLevel !=null || cinemaScore!=null || wantToSee!=null || otherScoreValue!=null) {
        	page.putField(MaoYanScoreSupplement.class.getName(), new MaoYanScoreSupplement(
            		dataId,
            		tvname,
            		score,
            		starLevel,
            		cinemaScore,
            		wantToSee,
            		otherScoreValue
            		));
        }
        
	}
	
	@SuppressWarnings({ "unused"})
	private String getStarLevel(List<String> list){
		Double starLevel = 0.0;
		if(list == null || list.size()<0)
		return null;
		for(String str: list){
			if(str.contains("fullstar")){
				starLevel +=1; 
			}else if(str.contains("halfstar")){
				starLevel+=0.5;
			}
		}
		return starLevel+"";
	}
	
	@Override
	protected String[] getStartRequestUrls() {
		return new String[]{START_URL[0]};
	}
	
	@Override
	protected String getSpiderType() {
		return Constants.SpiderTaskType.MOVIE_BOXOFFICE;
	}

	
	protected String convertDateStr(String str){
    	String first = str.substring(0,4);
    	String second = str.substring(4, 6);
    	String three = str.substring(6);
    	return first+"-"+second+"-"+three;
    }
	
}
